package com.aaa.data;

import com.aaa.config.SSLHelper;
import com.aaa.dto.BookCatalogueDto;
import com.aaa.service.BookService;
import com.aaa.service.impl.BookServiceImpl;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;

import static com.aaa.util.DataProcessing.splitList;

/**
 * @author 杨森
 * @version 1.0
 * @Title:
 * @date 2020/8/10 15:16
 */
public class DownloadBook {
    private static HttpServletRequest request;
    private static BookService bookService;
    private static ExecutorService executorService;
    private static final int count=3;
    public static void setDataSource(String bookCod, String bookName, String dataSource,
                                     HttpServletRequest request, BookServiceImpl bookService,ExecutorService executorService) {
        DownloadBook.request = request;
        DownloadBook.executorService = executorService;
        DownloadBook.bookService = bookService;
        SSLHelper.init();
        if ("biquge5200".equals(dataSource)) {
            try {
                String path = "/usr/local/webapps/file/" + bookName + ".txt";
                File file = new File(path);
                if (file.exists()) {
                    return;
                }
                List<BookCatalogueDto> bookCatalogueDto = bookService.getBookCatalogue(bookCod, request);
                Map<Integer, List<BookCatalogueDto>> integerListMap = splitList(bookCatalogueDto, count);
                long start = System.currentTimeMillis();
                CountDownLatch latch=new CountDownLatch(count);
                for (int i = 0; i < count; i++) {
                    final int ins=i+1;
                    executorService.execute(() -> {
                        try {
                            biquge5200(bookCod, bookName + ins, integerListMap.get(ins-1));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }finally {
                            latch.countDown();
                        }
                    });
                }
                latch.await();
                //合并文件
                combine(bookName);
                long end = System.currentTimeMillis();
                System.out.println("本次下载共用时"+(end-start));
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                executorService.shutdown();
            }
        } else if ("biquge".equals(dataSource)) {
            try {
                List<BookCatalogueDto> bookCatalogueDto = bookService.getBookCatalogue(bookCod, request);
                Map<Integer, List<BookCatalogueDto>> integerListMap = splitList(bookCatalogueDto, count);
                long start = System.currentTimeMillis();
                CountDownLatch latch=new CountDownLatch(count);
                for (int i = 0; i < count; i++) {
                    final int ins=i+1;
                    executorService.execute(() -> {
                        try {
                            biquge(bookCod, bookName + ins, integerListMap.get(0));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }finally {
                            latch.countDown();
                        }
                    });
                }
                latch.await();
                //合并文件
                combine(bookName);
                long end = System.currentTimeMillis();
                System.out.println("本次下载共用时"+(end-start));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                executorService.shutdown();
            }
        }
    }

    public static void biquge5200(String bookCod, String bookName, List<BookCatalogueDto> bookCatalogueDto) throws
            Exception {
        String path = "/usr/local/webapps/file/" + bookName + ".txt";
        File file = new File(path);
        if (!file.exists()) {
            File dir = new File(file.getParent());
            dir.mkdirs();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            return;
        }

        //创建一个输出流,将爬到的小说以txt形式保存在硬盘
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
        bookCatalogueDto.forEach(e -> {
            System.out.println(e.getCatalogueName() + "正在下载中。。。。" + Thread.currentThread().getName());
            Document document = null;
            try {
                document = Jsoup.connect("https://www.biquge5200.com/" + e.getBookCod() + "/" + e.getCatalogueCod() + ".html").get();
            } catch (IOException ioException) {
                try {
                    Thread.sleep(4000);
                    try {
                        document = Jsoup.connect("https://www.biquge5200.com/" + e.getBookCod() + "/" + e.getCatalogueCod() + ".html").get();
                    } catch (IOException exception) {
                        return;
                    }
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
            }
            Elements chapterName = document.select("h1");
            try {
                bw.write(chapterName.text());
                bw.newLine();
                bw.flush();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            Elements elements = document.select("#content");
            String html = elements.get(0).html().replace("<div id='content'>", "").replace("</div>", "");
            String replace = html.replace("<script>readx();</script>", "").replace("<script>chaptererror();</script>", "");
            try {
                String[] split = replace.replace("<p>", "").split("</p>");
                for (String s : split) {
                    bw.write(s);
                    bw.newLine();
                    bw.flush();
                }

            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        });
        try {
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void biquge(String bookCod, String bookName,List<BookCatalogueDto> bookCatalogueDto) throws FileNotFoundException {
        String path = "/usr/local/webapps/file/" + bookName + ".txt";
        File file = new File(path);
        if (!file.exists()) {
            File dir = new File(file.getParent());
            dir.mkdirs();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            return;
        }
        //创建一个输出流,将爬到的小说以txt形式保存在硬盘
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
        bookCatalogueDto.forEach(e -> {
            System.out.println(e.getCatalogueName() + "正在下载中。。。。");
            Document document = null;
            try {
                document = Jsoup.connect("https://www.biquge.com/" + e.getBookCod() + "/" + e.getCatalogueCod() + ".html").get();
            } catch (Exception e1) {
                try {
                    Thread.sleep(4000);
                    document = Jsoup.connect("https://www.biquge.com/" + e.getBookCod() + "/" + e.getCatalogueCod() + ".html").get();
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            }

            Elements chapterName = document.select("h1");
            try {
                bw.write(chapterName.text());
                bw.newLine();
                bw.flush();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            Elements elements = document.select("#content");
            String html = elements.get(0).html().replace("<div id='content'>", "").replace("</div>", "");
            String replace = html.replace("<script>readx();</script>", "").replace("<script>chaptererror();</script>", "");
            try {
                String[] split = replace.split("<br>");
                for (String s : split) {
                    bw.write(s);
                    bw.newLine();
                    bw.flush();
                }

            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        });
        try {
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void combine(String bookName) throws Exception {
        String bookPath = "/usr/local/webapps/file/" + bookName + ".txt";
        File file = new File(bookPath);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
        for (int i = 1; i < 4; i++) {
            String path = "/usr/local/webapps/file/" + bookName + i + ".txt";
            File file1 = new File(path);
            if (file1.exists()) {
                BufferedReader br = new BufferedReader(new FileReader(file1));
                String line;
                while (true) {
                    if ((line = br.readLine()) == null) {
                        br.close();
                        break;
                    }
                    bw.write(line);
                    bw.newLine();
                }
            }
            file1.delete();
        }
        bw.flush();
        bw.close();
    }
}
